<?php

namespace App\Http\Controllers\Admin;

use App\Models\App;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class AppController extends BaseController
{
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     * @throws \Exception
     */
    public function index()
    {

        return $this->view('admin.app.apps', ['items' => App::all()]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchUpdate(Request $request)
    {
        $items = $request->post('items');
        $eventType = $this->request->post('eventType');
        if ($eventType === 'delete') {
            App::whereIn('id', $items)->delete();
        }

        if ($eventType === 'enable') {
            App::whereIn('id', $items)->update(['state' => 1]);
        }

        if ($eventType === 'disable') {
            App::whereIn('id', $items)->update(['state' => 0]);
        }
        return ajaxReturn();
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function newApp(Request $request)
    {

        $id = $request->get('id');
        if ($id) {
            $app = App::find($id);
        } else {
            $app = new App();
            $app->appid = 'cg_' . md5_16(time());
            $app->secret = Str::random(32);
        }

        return $this->view('admin.app.newapp', compact('id', 'app'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function save(Request $request)
    {
        $id = $request->get('id', 0);
        $newapp = $request->post('app', []);
        if ($id) {
            App::find($id)->update($newapp);
        } else {
            App::create($newapp);
        }
        return $this->messager()->links([
            [trans('common.continue add'), admin_url('app/newapp')],
            [trans('common.back list'), admin_url('app')]
        ])->render();
    }
}
